import { message } from 'ant-design-vue'
import { type MaybeRefOrGetter, toValue } from 'vue'

interface UseCopyOptions {
  /**
   * @default true
   */
  tip?: boolean
}
let copyFn = function (toBeCopied: string): Promise<void> {
  if (typeof navigator.clipboard === 'object' && window.isSecureContext) {
    copyFn = function (toBeCopied: string) {
      return navigator.clipboard.writeText(toBeCopied)
    }
  }
  else {
    copyFn = function (toBeCopied: string) {
      return new Promise((resolve, reject) => {
        const textarea = document.createElement('textarea')
        textarea.value = toBeCopied
        document.body.append(textarea)
        textarea.select()
        try {
          document.execCommand('copy')
          resolve()
        }
        catch (error) {
          reject(error)
        }
        finally {
          document.body.removeChild(textarea)
        }
      })
    }
  }
  return copyFn(toBeCopied)
}
export function useCopy(text: MaybeRefOrGetter, opts?: UseCopyOptions) {
  opts = {
    tip: true,
    ...opts,
  }
  function copy() {
    return copyFn(toValue(text)).then(() => {
      if (opts!.tip) {
        message.success('复制成功')
      }
    })
  }
  return {
    copy,
  }
}
